﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

using P2PTransmit.Modal;
using P2PTransmit.Modal.Protocol;

namespace P2PTransmit.ViewModal.Service
{
    public class MessageService : ProtocolService<Message>,IDisposable
    {
        

        public MessageService(int port) : base( port )
        {
            base.OnReceive += Filter;
        }

        public new void Dispose()
        {
            started = false;
            base.OnReceive -= Filter;
            base.Dispose();
        }

        public void SendMessage(string content,string macAddress)
        {
            var Protocol = new MessageProtocol();
            var Message = new Message();
            Message.Content = content;
            Message.Author = ServiceManager.LocalMachineName;
            Message.Date = DateTime.Now.ToString();
            Protocol.Content = Message;
            Protocol.MacAddress = macAddress;
            base.Send( Serialize( Protocol ) );
        }

        private void Filter(string json ,IPEndPoint ip)
        {
            var protocol = Deserialize<MessageProtocol>( json );
            if(protocol.MacAddress == ServiceManager.LocalMacAddress)
            {
                OnMessageReceive?.Invoke();
                base.Pool.Add( protocol.Content );
            }
        }
        public event Action OnMessageReceive;
    }
}
